/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demo;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.JOptionPane;

/**
 *
 * @author PHINGUYEN
 */
public class TestSave {

    public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String input = "phi";
        String path = "C:/";
        System.out.println("Text: " + input);

        PublicKey pubKey;
        PrivateKey priKey;

        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(2048, new SecureRandom());
        KeyPair key = gen.generateKeyPair();

        pubKey = key.getPublic();
        priKey = key.getPrivate();



        SaveKeyPair(path, key);

//        SaveEncripted(encryptedOutput);
//        String str = new String(encryptedOutput);



//        String str = encryptedOutput.toString(); //chuyen sang string
//        System.out.println("encrypt text: "+ str);
//        
//        byte[] byt =str.getBytes(); //chuyen nguoc lai byte[]
//        byte[] decryptedOutput = DecryptRSA(byt, priKey); //giai ma ,neu ko chuyen sang string va chuyen nguoc lai byte ma truyen thang encryptedOutput vao thi giai ma duoc
//        System.out.println("Text decrypt:"+ new String(decryptedOutput));

        try {

            Class.forName(("com.microsoft.sqlserver.jdbc.SQLServerDriver"));
            System.out.println("load driver successfully...");
            Connection conn = DriverManager.getConnection("jdbc:sqlserver://ANHPHI;databaseName=TestEncrypt;user=sa;password=1234567");
            System.out.println("got connection.....");
            byte[] encryptedOutput = EncryptRSA(input, pubKey);
            PreparedStatement pstmt = null;
            String sql2 = "INSERT INTO Content(content) VALUES (?)";
            pstmt = conn.prepareStatement(sql2);
            pstmt.setBytes(1, encryptedOutput);

            int rowCount = pstmt.executeUpdate();
            conn.close();

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(TestSave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        
    }
//save key ma hoa xuong file

    public static void SaveKeyPair(String path, KeyPair key) throws FileNotFoundException, IOException {
        X509EncodedKeySpec x509 = new X509EncodedKeySpec((key.getPublic().getEncoded()));
        FileOutputStream fos = new FileOutputStream(path + "pub.key");
        fos.write(x509.getEncoded());
        fos.close();

        PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(key.getPrivate().getEncoded());
        fos = new FileOutputStream(path + "pri.key");
        fos.write(pkcs8.getEncoded());
        fos.close();
    }
//save file da ma hoa 

    public static void SaveEncripted(byte[] encrypted) throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream("d:/encrypt.txt");
        fos.write(encrypted);
        fos.close();
    }

    public static byte[] EncryptRSA(String str, PublicKey pubKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encryptedOutput = cipher.doFinal(str.getBytes());

        return encryptedOutput;
    }

    public static byte[] DecryptRSA(byte[] byte1, PrivateKey priKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, IllegalBlockSizeException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] decryptedOutput = cipher.doFinal(byte1);
        return decryptedOutput;
    }
}
